package com.su.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.su.common.exception.BizCodeEnume;
import com.su.common.to.es.SkuEsModel;
import com.su.common.utils.R;
import com.su.gulimall.search.config.GulimallElasticSearchConfig;
import com.su.gulimall.search.constant.EsConstant;
import com.su.gulimall.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService {

    @Autowired
    RestHighLevelClient restHighLevelClient;
    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {
        //该业务将product服务中的数据保存进es
        //创建发送请求
        //TODO 没有完成映射关系建立,此处在elasticsearch中使用
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel model : skuEsModels) {
            //指定索引的位置,实际值为product
            IndexRequest request = new IndexRequest(EsConstant.PRODUCT_INDEX);
            //指定相关的id是多少，此处尚有疑惑
            request.id(model.getSkuId().toString());
            //将模型数据转为json字符串
            String s = JSON.toJSONString(model);
            //循环放入IndexRequest中，并以json格式存储
            request.source(s, XContentType.JSON);
            //将其加入批量请求中
            bulkRequest.add(request);
        }
        //返回处理的结果
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);
        //分析保存结果
        List<String> collect = Arrays.stream(bulk.getItems()).map(item -> {
            return item.getId();
        }).collect(Collectors.toList());
        //获取商品上架的id
        log.info("商品上架成功: {}", collect);
        //返回布尔类型的数据，如果是true就是有错误了，
        boolean b = bulk.hasFailures();
        return b;
    }
}
